package com.LeeCode;

import java.util.Arrays;

/**
 * 旋转图像
 */
public class Code048 {
    public static void main(String[] args) {

        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        new Code048().rotate1(matrix);

        System.out.println(Arrays.deepToString(matrix));

    }

    public void rotate(int[][] matrix) {
        int n = matrix.length;
        int[][] tmp = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                tmp[j][n - 1 - i] = matrix[i][j];
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                matrix[i][j] = tmp[i][j];
            }
        }
    }

    public void rotate1(int[][] matrix) {
        /**
         * tmp是始终要重复用到的，在外面声明比在里面声明要省去重复开辟内存的开销
         */
        int n = matrix.length, tmp;
        // 上下反转
        for (int i = 0; i < n / 2; i++) {
            for (int j = 0; j < n; j++) {
                tmp = matrix[i][j];
                matrix[i][j] = matrix[n-1-i][j];
                matrix[n-1-i][j] = tmp;
            }
        }
        // 对角反转
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                tmp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = tmp;
            }
        }
    }
}
